# -*- coding: utf-8 -*-
# @Time : 2021/8/12 0012 15:24
# @Author : lyw
# @Remark : 门禁出入记录
import datetime
import re
import time
from typing import List

from db.common.IOTManager.Janitor.record import RecordDB

from model.common.IOTManager.Janitor.record import RecordModel
from mxsoftpy import Server
from utils.public.params_method import get_pagination_params, pagination


class RecordServer(Server):
    __db__ = RecordDB
    __model__ = RecordModel

    def get_record(self, **kwargs):

        # return query_param
        # return param
        query_param = self.process_param(kwargs)

        total, res_list = self.db.query_record(kwargs.get("type"), **query_param)
        # return [total,res_list]
        res_dict = {"data": res_list, "total": total}
        return pagination(res_dict, query_param, total)

    def process_param(self, kwargs):
        """
        参数
        @return:
        """
        if not kwargs.get("start_time"):
            kwargs["start_time"] = (datetime.datetime.now() - datetime.timedelta(days=30)).strftime("%Y-%m-%d %H:%M:%S")
        if not kwargs.get("end_time"):
            kwargs["end_time"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        param = self.model(**kwargs).dict()
        param["sortkey"] = "create_time"
        param["sortop"] = 1
        # return param
        # 判断是否导出调用
        if kwargs.get("type"):
            query_param = {"order_by": "create_time", "is_desc": True}
        else:
            query_param = get_pagination_params(param)

        query_param["create_time__gte"] = param["start_time"]
        query_param["create_time__lte"] = param["end_time"]

        param["personnel"] = param["personnel"].replace("*", "").replace(" ", "")
        param["door"] = param["door"].replace("*", "").replace(" ", "")
        param["door_id"] = param["door_id"].replace("*", "").replace(" ", "")

        if param["personnel"]:
            # personnel_list = self.db.query_personnel(name__like="*" + param["personnel"] + "*")
            # if personnel_list:
            #     # query_param["pers_id__in"] = personnel_list
            #     query_param["pers_id__in"] = [personnel_list[i] for i in range(495)] if len(
            #         personnel_list) > 495 else personnel_list
            # else:
            #     query_param["pers_id"] = ""
            query_param["name__like"] = "*%s*" % param["personnel"]

        if param["door_id"]:
            query_param["door_id__in"] = [param["door_id"]]
        if param["door"]:
            door_id = self.db.query_door(label__like="*" + param["door"] + "*")
            if door_id:
                query_param["door_id__in"] = door_id
        else:
            door_id_in= self.db.query_door(is_del=0)
            if door_id_in:
                query_param["door_id__in"] = door_id_in

        return query_param

    def get_count(self, door_list: List[dict]):
        """
        获取总数
        @return:
        """
        res_dict = {"total": 0, "in": 0, "out": 0}
        for door in door_list:
            query_param = {"create_time__gte": int(time.mktime(datetime.date.today().timetuple())),
                           "create_time__lte": datetime.datetime.now().timestamp(),
                           "door_id": door["code"]}

            total, record_list = self.db.query_record(True, **query_param)

            for record_value in record_list:
                if re.search("[出下]", record_value["record_value"]):
                    res_dict["out"] += 1
                elif re.search("[入上]", record_value["record_value"]):
                    res_dict["int"] += 1
            res_dict["total"] += 1
        return res_dict
